package com.dzm.xgb.core.controller.api;

import com.dzm.common.exception.Assert;
import com.dzm.common.result.R;
import com.dzm.common.result.ResponseEnum;
import com.dzm.common.util.JwtUtils;
import com.dzm.xgb.core.pojo.vo.LoginVo;
import com.dzm.xgb.core.pojo.vo.UserIndexVO;
import com.dzm.xgb.core.pojo.vo.UserInfoVo;
import com.dzm.xgb.core.service.UserInfoService;
import com.dzm.xgb.core.pojo.vo.RegisterVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 作者：Dzm
 * 时间：2024-08-27-11:52
 * 功能：
 */

@RestController
@RequestMapping("/api/core/userInfo")
@Api(tags = "用户信息接口")
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;

    @GetMapping("/auth/getIndexUserInfo")
    public R getUserInfo(@RequestHeader("token") String token) {
        Long userId = JwtUtils.getUserId(token);
        UserIndexVO vo = userInfoService.getUserIndexById(userId);

        return R.ok().data("userIndexVO", vo);
    }

    @GetMapping("/list")
    @ApiOperation("用户信息列表")
    public R list() {
        return R.ok().data("list", userInfoService.list());
    }

    @PostMapping("/register")
    @ApiOperation("用户注册")
    public R register(@RequestBody RegisterVo vo) {
        userInfoService.register(vo);

        return R.ok().message("注册成功！");
    }

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public R login(@RequestBody LoginVo vo, HttpServletRequest request) {
        String ip = request.getLocalAddr();
        UserInfoVo userInfo = userInfoService.login(vo, ip);

        return R.ok().data("userInfo", userInfo);
    }

    @GetMapping("/checkToken")
    @ApiOperation("令牌校验")
    public R checkToken(@RequestHeader(value = "token", required = false) String token) {
        boolean valid = JwtUtils.checkToken(token);
        Assert.isTrue(valid, ResponseEnum.LOGIN_AUTH_ERROR);

        return R.ok();
    }

    //校验手机号在userInfo表是否存在
    @ApiOperation("校验手机号是否存在")
    @GetMapping("/check/{phoneNumber}")
    public R checkPhone(@PathVariable("phoneNumber")String phoneNumber) {
        boolean isExist = userInfoService.checkPhone(phoneNumber);

        return R.ok().data("isExist", isExist);
    }
}
